package com.lianjia.sh.se.esb.server.kafka;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * Created by yangsp1 on 16/7/20.
 */
public class ConsumerManager2 {
    public Consumer<String, String> createConsumer() {
        Properties props = new Properties();
        //props.put("bootstrap.servers", "10.8.1.160:19092");
        props.put("bootstrap.servers", "10.8.1.160:19092,10.8.1.93:19092");
        props.put("group.id", "test2");//多个consumer，如果有相同groupId，则相当于队列，只有一个consumer消息，否则为订阅，为同时消费
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        return consumer;
    }

    public static void main(String args[]){
        ConsumerManager2 consumerManager = new ConsumerManager2();
        Consumer consumer = consumerManager.createConsumer();
        consumer.subscribe(Arrays.asList("my-topic"));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
                System.out.println();
            }
        }
    }
}
